package de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.nodeImpl;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.espertech.esper.client.EPServiceProvider;

import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.MMOperatorNode;
import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.NodeFactory;
import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.NodeFactoryManager;

public class ComposedCorrelationNodeFactory implements NodeFactory {

	public MMOperatorNode createNode(Element DOMElement,
			Element attachmentsElement, MMOperatorNode parent,
			EPServiceProvider EPService) {

		MMOperatorNode toReturn = new MMOperatorNode();

		// Attributes independent of the children
		toReturn.setOutputStreamName("correlationSet"
				+ (++MMOperatorNode.nodeLatestDistributedID));
		toReturn.setOutputMetric("correlationSet");

		toReturn.setParent(parent);

		/*
		 * Parameters to get : nothing
		 */

		// toReturn.setParameters();
		// Children nodes
		NodeList childrenElements = DOMElement.getChildNodes();
		if (childrenElements.getLength() > 0) {
			List<MMOperatorNode> children = new ArrayList<MMOperatorNode>(4);
			for (int i = 0; i < childrenElements.getLength(); i++) {
				Element currentChildRoot = (Element) childrenElements.item(i);
				children.add(NodeFactoryManager.getInstance(
						currentChildRoot.getLocalName()).createNode(
						currentChildRoot, attachmentsElement, toReturn,
						EPService));
			}

			toReturn.setChildren(children);
		}

		String statementString = null;

		statementString
				.concat("INSERT INTO "
						+ toReturn.getOutputStreamName()
						+ " SELECT "
						+ " de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.EventUtils.addInCorrelationSet(a.correlationSet, b.correlationSet) AS correlationSet "
						+ " FROM PATTERN [(every a = "
						+ toReturn.getChildren().get(0).getOutputStreamName()
						+ " -> b = "
						+ toReturn.getChildren().get(1).getOutputStreamName()
						+ "(de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.EventUtils.isSetIntersectionNonEmpty(a.correlationSet, b.correlationSet))"
						+ " OR (every b = "
						+ toReturn.getChildren().get(1).getOutputStreamName()
						+ " -> a = "
						+ toReturn.getChildren().get(0).getOutputStreamName()
						+ "(de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.EventUtils.isSetintersectionNonEmpty(a.correlationSet, b.correlationSet)"
						+ ")]");

		// Creation of the statement that is directly registered in the engine !
		toReturn.setStatement(EPService.getEPAdministrator().createEPL(
				statementString));

		return toReturn;
	}
}
